<?php

// 公共助手函数

use Symfony\Component\VarExporter\VarExporter;
use think\exception\HttpResponseException;
use app\admin\model\Configuration;
use app\admin\model\Shop;
use app\admin\model\DistributeTask;
use app\admin\model\ShopPriceLog;
use think\Response;
use think\Db;
use think\Exception;

function redis_init(){
    $redis = new \Redis();
    $redis->connect(config("redis.host"),config("redis.port"));
    $redis->auth(config("redis.auth"));
    return $redis;
}

if (!function_exists('__')) {

    /**
     * 获取语言变量值
     * @param string $name 语言变量名
     * @param array  $vars 动态变量值
     * @param string $lang 语言
     * @return mixed
     */
    function __($name, $vars = [], $lang = '')
    {
        if (is_numeric($name) || !$name) {
            return $name;
        }
        if (!is_array($vars)) {
            $vars = func_get_args();
            array_shift($vars);
            $lang = '';
        }
        return \think\Lang::get($name, $vars, $lang);
    }
}
function dd($var)
{
    var_dump($var);
    die;
}

if (!function_exists('format_bytes')) {

    /**
     * 将字节转换为可读文本
     * @param int    $size      大小
     * @param string $delimiter 分隔符
     * @param int    $precision 小数位数
     * @return string
     */
    function format_bytes($size, $delimiter = '', $precision = 2)
    {
        $units = array('B', 'KB', 'MB', 'GB', 'TB', 'PB');
        for ($i = 0; $size >= 1024 && $i < 6; $i++) {
            $size /= 1024;
        }
        return round($size, $precision) . $delimiter . $units[$i];
    }
}

if (!function_exists('datetime')) {

    /**
     * 将时间戳转换为日期时间
     * @param int    $time   时间戳
     * @param string $format 日期时间格式
     * @return string
     */
    function datetime($time, $format = 'Y-m-d H:i:s')
    {
        $time = is_numeric($time) ? $time : strtotime($time);
        return date($format, $time);
    }
}

if (!function_exists('human_date')) {

    /**
     * 获取语义化时间
     * @param int $time  时间
     * @param int $local 本地时间
     * @return string
     */
    function human_date($time, $local = null)
    {
        return \fast\Date::human($time, $local);
    }
}

if (!function_exists('cdnurl')) {

    /**
     * 获取上传资源的CDN的地址
     * @param string  $url    资源相对地址
     * @param boolean $domain 是否显示域名 或者直接传入域名
     * @return string
     */
    function cdnurl($url, $domain = false)
    {
        $regex = "/^((?:[a-z]+:)?\/\/|data:image\/)(.*)/i";
        $cdnurl = \think\Config::get('upload.cdnurl');
        $url = preg_match($regex, $url) || ($cdnurl && stripos($url, $cdnurl) === 0) ? $url : $cdnurl . $url;
        if ($domain && !preg_match($regex, $url)) {
            $domain = is_bool($domain) ? request()->domain() : $domain;
            $url = $domain . $url;
        }
        return $url;
    }
}


if (!function_exists('is_really_writable')) {

    /**
     * 判断文件或文件夹是否可写
     * @param string $file 文件或目录
     * @return    bool
     */
    function is_really_writable($file)
    {
        if (DIRECTORY_SEPARATOR === '/') {
            return is_writable($file);
        }
        if (is_dir($file)) {
            $file = rtrim($file, '/') . '/' . md5(mt_rand());
            if (($fp = @fopen($file, 'ab')) === false) {
                return false;
            }
            fclose($fp);
            @chmod($file, 0777);
            @unlink($file);
            return true;
        } elseif (!is_file($file) or ($fp = @fopen($file, 'ab')) === false) {
            return false;
        }
        fclose($fp);
        return true;
    }
}

if (!function_exists('rmdirs')) {

    /**
     * 删除文件夹
     * @param string $dirname  目录
     * @param bool   $withself 是否删除自身
     * @return boolean
     */
    function rmdirs($dirname, $withself = true)
    {
        if (!is_dir($dirname)) {
            return false;
        }
        $files = new RecursiveIteratorIterator(
            new RecursiveDirectoryIterator($dirname, RecursiveDirectoryIterator::SKIP_DOTS),
            RecursiveIteratorIterator::CHILD_FIRST
        );

        foreach ($files as $fileinfo) {
            $todo = ($fileinfo->isDir() ? 'rmdir' : 'unlink');
            $todo($fileinfo->getRealPath());
        }
        if ($withself) {
            @rmdir($dirname);
        }
        return true;
    }
}

if (!function_exists('copydirs')) {

    /**
     * 复制文件夹
     * @param string $source 源文件夹
     * @param string $dest   目标文件夹
     */
    function copydirs($source, $dest)
    {
        if (!is_dir($dest)) {
            mkdir($dest, 0755, true);
        }
        foreach (
            $iterator = new RecursiveIteratorIterator(
                new RecursiveDirectoryIterator($source, RecursiveDirectoryIterator::SKIP_DOTS),
                RecursiveIteratorIterator::SELF_FIRST
            ) as $item
        ) {
            if ($item->isDir()) {
                $sontDir = $dest . DS . $iterator->getSubPathName();
                if (!is_dir($sontDir)) {
                    mkdir($sontDir, 0755, true);
                }
            } else {
                copy($item, $dest . DS . $iterator->getSubPathName());
            }
        }
    }
}

if (!function_exists('mb_ucfirst')) {
    function mb_ucfirst($string)
    {
        return mb_strtoupper(mb_substr($string, 0, 1)) . mb_strtolower(mb_substr($string, 1));
    }
}

if (!function_exists('addtion')) {

    /**
     * 附加关联字段数据
     * @param array $items  数据列表
     * @param mixed $fields 渲染的来源字段
     * @return array
     */
    function addtion($items, $fields)
    {
        if (!$items || !$fields) {
            return $items;
        }
        $fieldsArr = [];
        if (!is_array($fields)) {
            $arr = explode(',', $fields);
            foreach ($arr as $k => $v) {
                $fieldsArr[$v] = ['field' => $v];
            }
        } else {
            foreach ($fields as $k => $v) {
                if (is_array($v)) {
                    $v['field'] = isset($v['field']) ? $v['field'] : $k;
                } else {
                    $v = ['field' => $v];
                }
                $fieldsArr[$v['field']] = $v;
            }
        }
        foreach ($fieldsArr as $k => &$v) {
            $v = is_array($v) ? $v : ['field' => $v];
            $v['display'] = isset($v['display']) ? $v['display'] : str_replace(['_ids', '_id'], ['_names', '_name'], $v['field']);
            $v['primary'] = isset($v['primary']) ? $v['primary'] : '';
            $v['column'] = isset($v['column']) ? $v['column'] : 'name';
            $v['model'] = isset($v['model']) ? $v['model'] : '';
            $v['table'] = isset($v['table']) ? $v['table'] : '';
            $v['name'] = isset($v['name']) ? $v['name'] : str_replace(['_ids', '_id'], '', $v['field']);
        }
        unset($v);
        $ids = [];
        $fields = array_keys($fieldsArr);
        foreach ($items as $k => $v) {
            foreach ($fields as $m => $n) {
                if (isset($v[$n])) {
                    $ids[$n] = array_merge(isset($ids[$n]) && is_array($ids[$n]) ? $ids[$n] : [], explode(',', $v[$n]));
                }
            }
        }
        $result = [];
        foreach ($fieldsArr as $k => $v) {
            if ($v['model']) {
                $model = new $v['model'];
            } else {
                $model = $v['name'] ? \think\Db::name($v['name']) : \think\Db::table($v['table']);
            }
            $primary = $v['primary'] ? $v['primary'] : $model->getPk();
            $result[$v['field']] = isset($ids[$v['field']]) ? $model->where($primary, 'in', $ids[$v['field']])->column($v['column'], $primary) : [];
        }

        foreach ($items as $k => &$v) {
            foreach ($fields as $m => $n) {
                if (isset($v[$n])) {
                    $curr = array_flip(explode(',', $v[$n]));

                    $linedata = array_intersect_key($result[$n], $curr);
                    $v[$fieldsArr[$n]['display']] = $fieldsArr[$n]['column'] == '*' ? $linedata : implode(',', $linedata);
                }
            }
        }
        return $items;
    }
}

if (!function_exists('var_export_short')) {

    /**
     * 使用短标签打印或返回数组结构
     * @param mixed   $data
     * @param boolean $return 是否返回数据
     * @return string
     */
    function var_export_short($data, $return = true)
    {
        return var_export($data, $return);
        $replaced = [];
        $count = 0;

        //判断是否是对象
        if (is_resource($data) || is_object($data)) {
            return var_export($data, $return);
        }

        //判断是否有特殊的键名
        $specialKey = false;
        array_walk_recursive($data, function (&$value, &$key) use (&$specialKey) {
            if (is_string($key) && (stripos($key, "\n") !== false || stripos($key, "array (") !== false)) {
                $specialKey = true;
            }
        });
        if ($specialKey) {
            return var_export($data, $return);
        }
        array_walk_recursive($data, function (&$value, &$key) use (&$replaced, &$count, &$stringcheck) {
            if (is_object($value) || is_resource($value)) {
                $replaced[$count] = var_export($value, true);
                $value = "##<{$count}>##";
            } else {
                if (is_string($value) && (stripos($value, "\n") !== false || stripos($value, "array (") !== false)) {
                    $index = array_search($value, $replaced);
                    if ($index === false) {
                        $replaced[$count] = var_export($value, true);
                        $value = "##<{$count}>##";
                    } else {
                        $value = "##<{$index}>##";
                    }
                }
            }
            $count++;
        });

        $dump = var_export($data, true);

        $dump = preg_replace('#(?:\A|\n)([ ]*)array \(#i', '[', $dump); // Starts
        $dump = preg_replace('#\n([ ]*)\),#', "\n$1],", $dump); // Ends
        $dump = preg_replace('#=> \[\n\s+\],\n#', "=> [],\n", $dump); // Empties
        $dump = preg_replace('#\)$#', "]", $dump); //End

        if ($replaced) {
            $dump = preg_replace_callback("/'##<(\d+)>##'/", function ($matches) use ($replaced) {
                return isset($replaced[$matches[1]]) ? $replaced[$matches[1]] : "''";
            }, $dump);
        }

        if ($return === true) {
            return $dump;
        } else {
            echo $dump;
        }
    }
}

if (!function_exists('letter_avatar')) {
    /**
     * 首字母头像
     * @param $text
     * @return string
     */
    function letter_avatar($text)
    {
        $total = unpack('L', hash('adler32', $text, true))[1];
        $hue = $total % 360;
        list($r, $g, $b) = hsv2rgb($hue / 360, 0.3, 0.9);

        $bg = "rgb({$r},{$g},{$b})";
        $color = "#ffffff";
        $first = mb_strtoupper(mb_substr($text, 0, 1));
        $src = base64_encode('<svg xmlns="http://www.w3.org/2000/svg" version="1.1" height="100" width="100"><rect fill="' . $bg . '" x="0" y="0" width="100" height="100"></rect><text x="50" y="50" font-size="50" text-copy="fast" fill="' . $color . '" text-anchor="middle" text-rights="admin" dominant-baseline="central">' . $first . '</text></svg>');
        $value = 'data:image/svg+xml;base64,' . $src;
        return $value;
    }
}

if (!function_exists('hsv2rgb')) {
    function hsv2rgb($h, $s, $v)
    {
        $r = $g = $b = 0;

        $i = floor($h * 6);
        $f = $h * 6 - $i;
        $p = $v * (1 - $s);
        $q = $v * (1 - $f * $s);
        $t = $v * (1 - (1 - $f) * $s);

        switch ($i % 6) {
            case 0:
                $r = $v;
                $g = $t;
                $b = $p;
                break;
            case 1:
                $r = $q;
                $g = $v;
                $b = $p;
                break;
            case 2:
                $r = $p;
                $g = $v;
                $b = $t;
                break;
            case 3:
                $r = $p;
                $g = $q;
                $b = $v;
                break;
            case 4:
                $r = $t;
                $g = $p;
                $b = $v;
                break;
            case 5:
                $r = $v;
                $g = $p;
                $b = $q;
                break;
        }

        return [
            floor($r * 255),
            floor($g * 255),
            floor($b * 255)
        ];
    }
}

if (!function_exists('check_nav_active')) {
    /**
     * 检测会员中心导航是否高亮
     */
    function check_nav_active($url, $classname = 'active')
    {
        $auth = \app\common\library\Auth::instance();
        $requestUrl = $auth->getRequestUri();
        $url = ltrim($url, '/');
        return $requestUrl === str_replace(".", "/", $url) ? $classname : '';
    }
}

if (!function_exists('check_cors_request')) {
    /**
     * 跨域检测
     */
    function check_cors_request()
    {
        if (isset($_SERVER['HTTP_ORIGIN']) && $_SERVER['HTTP_ORIGIN']) {
            $info = parse_url($_SERVER['HTTP_ORIGIN']);
            $domainArr = explode(',', config('fastadmin.cors_request_domain'));
            $domainArr[] = request()->host(true);
            if (in_array("*", $domainArr) || in_array($_SERVER['HTTP_ORIGIN'], $domainArr) || (isset($info['host']) && in_array($info['host'], $domainArr))) {
                header("Access-Control-Allow-Origin: " . $_SERVER['HTTP_ORIGIN']);
            } else {
                $response = Response::create('跨域检测无效', 'html', 403);
                throw new HttpResponseException($response);
            }

            header('Access-Control-Allow-Credentials: true');
            header('Access-Control-Max-Age: 86400');

            if ($_SERVER['REQUEST_METHOD'] == 'OPTIONS') {
                if (isset($_SERVER['HTTP_ACCESS_CONTROL_REQUEST_METHOD'])) {
                    header("Access-Control-Allow-Methods: GET, POST, PUT, DELETE, OPTIONS");
                }
                if (isset($_SERVER['HTTP_ACCESS_CONTROL_REQUEST_HEADERS'])) {
                    header("Access-Control-Allow-Headers: {$_SERVER['HTTP_ACCESS_CONTROL_REQUEST_HEADERS']}");
                }
                $response = Response::create('', 'html');
                throw new HttpResponseException($response);
            }
        }
    }
}
if (!function_exists('is_english')) {
    function is_english($str)
    {
        if(preg_match("/^[a-zA-Z\s]+$/",$str)){
            return true;
        }
        return false;
    }
}

if (!function_exists('xss_clean')) {
    /**
     * 清理XSS
     */
    function xss_clean($content, $is_image = false)
    {
        return \app\common\library\Security::instance()->xss_clean($content, $is_image);
    }
}

if (!function_exists('check_ip_allowed')) {
    /**
     * 检测IP是否允许
     * @param string $ip IP地址
     */
    function check_ip_allowed($ip = null)
    {
        $ip = is_null($ip) ? request()->ip() : $ip;
        $forbiddenipArr = config('site.forbiddenip');
        $forbiddenipArr = !$forbiddenipArr ? [] : $forbiddenipArr;
        $forbiddenipArr = is_array($forbiddenipArr) ? $forbiddenipArr : array_filter(explode("\n", str_replace("\r\n", "\n", $forbiddenipArr)));
        if ($forbiddenipArr && \Symfony\Component\HttpFoundation\IpUtils::checkIp($ip, $forbiddenipArr)) {
            $response = Response::create('请求无权访问', 'html', 403);
            throw new HttpResponseException($response);
        }
    }
}

if (!function_exists('build_suffix_image')) {
    /**
     * 生成文件后缀图片
     * @param string $suffix 后缀
     * @param null   $background
     * @return string
     */
    function build_suffix_image($suffix, $background = null)
    {
        $suffix = mb_substr(strtoupper($suffix), 0, 4);
        $total = unpack('L', hash('adler32', $suffix, true))[1];
        $hue = $total % 360;
        list($r, $g, $b) = hsv2rgb($hue / 360, 0.3, 0.9);

        $background = $background ? $background : "rgb({$r},{$g},{$b})";

        $icon = <<<EOT
        <svg version="1.1" xmlns="http://www.w3.org/2000/svg" xmlns:xlink="http://www.w3.org/1999/xlink" x="0px" y="0px" viewBox="0 0 512 512" style="enable-background:new 0 0 512 512;" xml:space="preserve">
            <path style="fill:#E2E5E7;" d="M128,0c-17.6,0-32,14.4-32,32v448c0,17.6,14.4,32,32,32h320c17.6,0,32-14.4,32-32V128L352,0H128z"/>
            <path style="fill:#B0B7BD;" d="M384,128h96L352,0v96C352,113.6,366.4,128,384,128z"/>
            <polygon style="fill:#CAD1D8;" points="480,224 384,128 480,128 "/>
            <path style="fill:{$background};" d="M416,416c0,8.8-7.2,16-16,16H48c-8.8,0-16-7.2-16-16V256c0-8.8,7.2-16,16-16h352c8.8,0,16,7.2,16,16 V416z"/>
            <path style="fill:#CAD1D8;" d="M400,432H96v16h304c8.8,0,16-7.2,16-16v-16C416,424.8,408.8,432,400,432z"/>
            <g><text><tspan x="220" y="380" font-size="124" font-family="Verdana, Helvetica, Arial, sans-serif" fill="white" text-anchor="middle">{$suffix}</tspan></text></g>
        </svg>
EOT;
        return $icon;
    }
}
function check_phone($phone){
    $check = '/^(1(([123456789][0-9])|(47)))\d{8}$/';
    if (preg_match($check, $phone)){
        return true;
    } else {
        return false;
    }
} 

function send_mobile($mobile,$TemplateCode = ''){
    $code=rand(100000,999999);
    //发送短信验证码，待接入
    $configuration=Configuration::find();
    // 注意使用GMT时间  
    date_default_timezone_set("GMT");  
    $target = "https://dysmsapi.aliyuncs.com/?";  
    $accessKeyId = $configuration['access_key'];      // 这里填写您的Access Key ID  
    $accessKeySecret = $configuration['access_secret'];  // 这里填写您的Access Key Secret  
    $ParamString="{\"code\":\"$code\"}";  
    $data = [
        'AccessKeyId' => $accessKeyId,
        'Action' => 'SendSms',
        'Format' => 'XML', 
        'OutId' => '123', 
        'PhoneNumbers' => $mobile,
        'RegionId' => 'cn-hangzhou',
        'SignName'=>$configuration['sign_name'],
        'SignatureMethod' => 'HMAC-SHA1',
        'SignatureNonce'=> '45e25e9b-0a6f-4070-8c85-'.uniqid(),
        'SignatureVersion' => '1.0',
        'TemplateCode' =>  $TemplateCode ? $TemplateCode : $configuration['sms_mb'], 
        'TemplateParam' => $TemplateCode ? '{}' : $ParamString,
        'Timestamp' => date("Y-m-d H:i:s"),
        'Version' => '2017-05-25'
    ];  
    $data['Signature'] = computeSignature($data, $accessKeySecret);  
    // 发送请求  
    $result = xml_to_array(https_request($target.http_build_query($data)));
    if(!empty($result['Error']['Message'])){
        return ['code'=>-1,'msg'=>$result['Error']['Message']];
    }else{
        return ['code'=>1,'code'=>$code];
    }
}


function computeSignature($parameters, $accessKeySecret)  {  
    // 将参数Key按字典顺序排序  
    ksort($parameters);  
    // 生成规范化请求字符串  
    $canonicalizedQueryString = '';  
    foreach($parameters as $key => $value)  {  
        $canonicalizedQueryString .= '&' . percentEncode($key)  
        . '=' . percentEncode($value);  
    }  
    // 生成用于计算签名的字符串 stringToSign  
    $stringToSign = 'GET&%2F&' . percentencode(substr($canonicalizedQueryString, 1));  
    //echo "<br>".$stringToSign."<br>";  
    // 计算签名，注意accessKeySecret后面要加上字符'&'  
    $signature = base64_encode(hash_hmac('sha1', $stringToSign, $accessKeySecret . '&', true));  
    return $signature;  
}
function percentEncode($str)  {  
    // 使用urlencode编码后，将"+","*","%7E"做替换即满足ECS API规定的编码规范  
    $res = urlencode($str);  
    $res = preg_replace('/\+/', '%20', $res);  
    $res = preg_replace('/\*/', '%2A', $res);  
    $res = preg_replace('/%7E/', '~', $res);  
    return $res;  
} 
function xml_to_array($xml){  
    $reg = "/<(\w+)[^>]*>([\\x00-\\xFF]*)<\\/\\1>/";  
    if(preg_match_all($reg, $xml, $matches)){  
        $count = count($matches[0]);  
        for($i = 0; $i < $count; $i++){  
        $subxml= $matches[2][$i];  
        $key = $matches[1][$i];  
            if(preg_match( $reg, $subxml )){  
                $arr[$key] = xml_to_array( $subxml );  
            }else{  
                $arr[$key] = $subxml;  
            }  
        }  
    }  
    return @$arr;  
}  
function https_request($url){  
    $curl = curl_init();  
    curl_setopt($curl, CURLOPT_URL, $url);  
    curl_setopt($curl, CURLOPT_SSL_VERIFYPEER, FALSE);  
    curl_setopt($curl, CURLOPT_SSL_VERIFYHOST, FALSE);  
    curl_setopt($curl, CURLOPT_RETURNTRANSFER, 1);  
    $data = curl_exec($curl);  
    if (curl_errno($curl)) {return 'ERROR '.curl_error($curl);}  
    curl_close($curl);  
    return $data;  
} 
function rose_level($total){
    if($total<=200){
        return 1;
    }elseif($total<=2000){
        return 2;
    }elseif($total<=5000){
        return 3;
    }elseif($total<=10000){
        return 4;
    }else{
        return 5;
    }
    
}


/**
 * @param string $address 详细地址  格式：福建省厦门市思明区中山路
 * @return array
 */
function get_LonandLat($address){
    $address = $address;
    $url = "http://apis.map.qq.com/ws/geocoder/v1/?address=$address&key=CZ2BZ-NAVHB-2PFUY-JRJF3-PD5DS-43BDC";  
    // 初始url会话
    $ch = curl_init(); 
    //  设置url传输选项 
    curl_setopt($ch, CURLOPT_URL, $url);
    curl_setopt($ch, CURLOPT_RETURNTRANSFER, 1); 
    // 执行url会话
    $result  = curl_exec($ch);
    if($result){
        $data = array();
        $res= json_decode($result ,true); 
        if ($res['status'] == 0) {
            $results = $res['result'];
            $data['lng'] = $results['location']['lng'];
            $data['lat'] = $results['location']['lat'];
        }
        return $data;
    }else{
        return 0;
    }
}


function level_name($total){
    if($total<=500){
        return '一心会员';
    }elseif($total<=2000){
        return '二心会员';
    }elseif($total<=5000){
        return '三心会员';
    }elseif($total<=10000){
        return '四心会员';
    }else{
        return '五心会员';
    }
}
function httpRequest($url,$data,$type){
    if($type=='json'){//json $_POST=json_decode(file_get_contents('php://input'), TRUE);
        $headers = array("Content-type: application/json;charset=UTF-8","Accept: application/json","Cache-Control: no-cache", "Pragma: no-cache");
        $data=json_encode($data);
    }
    $curl = curl_init();
    curl_setopt($curl, CURLOPT_URL, $url);
    curl_setopt($curl, CURLOPT_SSL_VERIFYPEER, FALSE);
    curl_setopt($curl, CURLOPT_SSL_VERIFYHOST, FALSE);
    if (!empty($data)){
    curl_setopt($curl, CURLOPT_POST, 1);
    curl_setopt($curl, CURLOPT_POSTFIELDS,$data);
    }
    curl_setopt($curl, CURLOPT_RETURNTRANSFER, 1);
    curl_setopt( $curl, CURLOPT_HTTPHEADER, $headers ); 
    $output = curl_exec($curl);
    curl_close($curl);
    return $output;
   }


//记录注册日志
function roseandlog($uid,$rose_money,$type,$title){
    $user_rose_money = db('user')->where(array('id'=>$uid))->value('rose_money');
    db('user')->where(array('id'=>$uid))->update(['rose_money'=>$rose_money+$user_rose_money]);
    db('user_rose_log')->insert(array('user_id'=>$uid,'title'=>$title,'type'=>$type,'rose_money'=>$rose_money,'add_time'=>time()));
}
function getWishImg($b){

    $arr = [
        'https://oa.yuxiang123.cn/uploads/20231017/5db13c092597913dffc2748e3b09326c.jpg',
        'https://oa.yuxiang123.cn/uploads/20231017/4b0b9ff62fa387c9b12afa746b4f259d.jpg',
        'https://oa.yuxiang123.cn/uploads/20231017/7afa43344e9c52dce41da2b6f8e7756f.jpg',
        'https://oa.yuxiang123.cn/uploads/20231017/f89562d678867305682f04421200d6ae.jpg',
        'https://oa.yuxiang123.cn/uploads/20231017/5ea8ffa9ac450bd02ba32c139a6e16e9.jpg',
        'https://oa.yuxiang123.cn/uploads/20231017/ccd064d930fb4458fd8f060223d6dcf1.jpg',
    ];
    return $arr[rand(0,5)];
    

    if($b['category_id'] == 19){ //其他
        $b['imgs'] = 'https://app.yuxiang123.cn/Public/xcx_img/qita.png';
    }elseif($b['category_id'] == 54){ //图书
        $b['imgs'] = 'https://app.yuxiang123.cn/Public/xcx_img/tushu.png';
    }elseif($b['category_id'] == 51){ //数码
        $b['imgs'] = 'https://app.yuxiang123.cn/Public/xcx_img/shuma.png';
    }elseif($b['category_id'] == 12){ //母婴
        $b['imgs'] = 'https://app.yuxiang123.cn/Public/xcx_img/muying.png';
    }elseif($b['category_id'] == 43){ //办公
        $b['imgs'] = 'https://app.yuxiang123.cn/Public/xcx_img/bangong.png';
    }elseif($b['category_id'] == 2){ //家具
        $b['imgs'] = 'https://app.yuxiang123.cn/Public/xcx_img/jiaju.png';
    }elseif($b['category_id'] == 5){ //服装
        $b['imgs'] = 'https://app.yuxiang123.cn/Public/xcx_img/fuzhuang.png';
    }
    return $b['imgs'];
}
function timeago($time){
    $now=time();
    $ago=$now-$time;
    if($ago<60*5){
        return '刚刚';
    }elseif($ago<60*60){
        return (floor($ago/60)).'分钟前';
    }elseif($ago<60*60*24){
        return (floor($ago/3600)).'小时前';
    }elseif($ago<60*60*24*30){
        return (floor($ago/3600/24)).'天前';
    }elseif($ago<60*60*24*30*12){
        return (floor($ago/3600/24/30)).'个月前';
    }else{
        return date("Y-m-d",$time);   
    }
}
function juli($juli){
    if($juli>1){
        if(strlen($juli)>3){
            return round($juli,0).'km';
        }else{
            return round($juli,1).'km';
        }
    }else{
        return ($juli*1000).'m';
    }
}

function getDistance($lat1, $lng1, $lat2, $lng2){
    $EARTH_RADIUS = 6378.137;
    $radLat1 = $lat1* M_PI / 180.0;
    $radLat2 = $lat2* M_PI / 180.0;
    $a = $radLat1 - $radLat2;
    $b = $lng1* M_PI / 180.0 - $lng2* M_PI / 180.0;
    $s = 2 * asin(sqrt(pow(sin($a / 2), 2) + cos($radLat1) * cos($radLat2) * pow(sin($b / 2), 2)));
    $s = $s * $EARTH_RADIUS;
    $s = round($s * 10000) / 10000;
    return $s;
}
function is_ship_num($ship_num){
    if(strlen($ship_num)>9 && strlen($ship_num)<16){
        $middle=substr($ship_num,2,strlen($ship_num)-4);
        if(!is_numeric($middle)){
            return false;
        }
    }else{
        return false;
    }
    return true;
}


//发送订阅推送消息
if (!function_exists('send_subscription')) {

    /**
     * 发送订阅推送消息
     * @param string $user_id  发送人user_id
     * @param mixed  $template_id 订阅模版id
     * @param mixed  $page  点击模版卡片跳转URL
     * @param mixed  $data  模版内容
     * @return string
     */
    function send_subscription($user_id, $template_id,$page,$data)
    {
        //发送订阅推送
        $openid=db('user')->where(array('id'=>$user_id))->value('openId');
        if($openid){
            $token_res=json_decode(file_get_contents('https://api.weixin.qq.com/cgi-bin/token?grant_type=client_credential&appid=wx7e02d2ebf871c207&secret=1048ec4292504f8f4b1423b205ddb9b8'),true);
            $token=$token_res['access_token'];

            $datas=array(
                "touser"=> $openid, //接收者（用户）的 openid
                "template_id"=> $template_id, //所需下发的订阅模板id
                "page"=>$page, //点击模板卡片后的跳转页面
                "data"=>$data, //模板内容，格式形如 { "key1": { "value": any }, "key2": { "value": any } }
                "miniprogram_state"=> 'formal' //跳转小程序类型：developer为开发版；trial为体验版；formal为正式版；默认为正式版
            );
            $data_string = json_encode((Object)$datas);
            $ch = curl_init('https://api.weixin.qq.com/cgi-bin/message/subscribe/send?access_token='.$token);
            curl_setopt($ch, CURLOPT_CUSTOMREQUEST, "POST");
            curl_setopt($ch, CURLOPT_POSTFIELDS,$data_string);
            curl_setopt($ch, CURLOPT_RETURNTRANSFER,true);
            curl_setopt($ch, CURLOPT_HTTPHEADER, array(
                'Content-Type: application/json',
                'Content-Length: ' . strlen($data_string))
            );
            $res = curl_exec($ch);
            curl_close($ch);
            db('log')->insert(['text'=>json_encode($res)]);
        }
    }
}


//更新商户余额账号信息
if (!function_exists('set_shop_task_price')) {
    /**
     * 更新商户余额账号信息
     * @param string $task_id_arr  任务id一维数组
     * @param mixed  $type 状态 1任务被退回/被取消  2任务已完成
     * @param mixed  $price  解冻需要扣除实际金额
     * @return string
     */
    function set_shop_task_price($task_id_arr, $type, $price = 0)
    {
        Db::startTrans();
            try {
                $list = DistributeTask::where(['id'=>['in',$task_id_arr]])->select();
                foreach ($list as $v) {   
                    $shop_id = Shop::where(['name'=>$v['type']])->value('id');
                    if(!$shop_id){
                        continue;
                    }
                    $where = [
                        'task_id'=>$v['id'],
                        'shop_id'=>$shop_id,
                        'is_freeze'=>1,
                        'freeze_type'=>0
                    ];
                    $info = ShopPriceLog::where($where)->find();
                    if(!$info){
                        return false;
                    }
                    //任务被退回/被取消
                    if($type == 1){
                        //查询到数据则进行解冻操作
                        ShopPriceLog::where(['id'=>$info['id']])->update(['freeze_type'=>1]);
                        $arr = [
                            'user_id'=>$info['user_id'],
                            'shop_id'=>$info['shop_id'],
                            'task_id'=>$info['task_id'],
                            'price'=>$info['price'],
                            'type'=>3,
                            'add_time'=>time(),
                        ];
                        ShopPriceLog::insert($arr);
                        $shop = Shop::where(['id'=>$shop_id])->find();
                        Shop::where(['id'=>$shop_id])->update(['balance'=>$shop['balance'] + $info['price']]);
                    }elseif($type == 2){ //任务已完成
                        ShopPriceLog::where(['id'=>$info['id']])->update(['freeze_type'=>1]);
                        $arr = [
                            'user_id'=>$info['user_id'],
                            'shop_id'=>$info['shop_id'],
                            'task_id'=>$info['task_id'],
                            'price'=>$info['price'],
                            'type'=>3,
                            'add_time'=>time(),
                        ];
                        ShopPriceLog::insert($arr);
                        //该任务需要支付多少钱
                        $arr = [
                            'user_id'=>$info['user_id'],
                            'shop_id'=>$info['shop_id'],
                            'task_id'=>$info['task_id'],
                            'price'=>$price,
                            'type'=>1,
                            'add_time'=>time(),
                        ];  
                        ShopPriceLog::insert($arr);
                        //判断冻结金额是否大于所支出金额  大于则把多余的钱还给商家   不大于则不需要
                        if($info['price'] > $price){
                            $shop = Shop::where(['id'=>$shop_id])->find();
                            Shop::where(['id'=>$shop_id])->update(['balance'=>$shop['balance'] + ($info['price']-$price)]);
                        }
                    }
                }


                
            Db::commit();
            return true;
        } catch (Exception $e) {
            Db::rollback();
            return false;
        }
    }
}